package com.bangdao.hu.roomba.Views;

import static com.bangdao.hu.TestBluetoothActivity.btThread;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.bangdao.hu.R;
import com.bangdao.hu.roomba.WifiSignalStrengthMap.MapGenerator;
import com.bangdao.hu.roomba.WifiSignalStrengthMap.MapPoint;
import com.bangdao.hu.roomba.helper.Helper;
import com.bangdao.hu.roomba.localizer.Localizer;

public class MapGenerationView extends Activity {
	private int yPos, xPos = 0;
	private float turningRadius = 0;
	private double orientation;
//	static public WifiManager wifiManager;
//	static public AssetManager assetManager;
	private Button mapGenButton;
	private Button localizeButton;
	private Button sendProbButton;
	private Button particleGenButton;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.map_gen);
		setupViews();
		//parseMapFile();
//		wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
//		assetManager = getAssets();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	void setupViews() {
		mapGenButton = (Button) findViewById(R.id.map_gen);
		particleGenButton = (Button) findViewById(R.id.particleGenButton);
		localizeButton = (Button)findViewById(R.id.localize);
		sendProbButton = (Button)findViewById(R.id.sendProbButton);
		
		sendProbButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				sendProb();
			}
		});
		
		mapGenButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Helper.parseMapFile();
				
				// generateMap();
				// MapGenerator.getInstance().parseMapFile();
				System.out.println("***********************************************");
//				for (MapPoint mp: MapGenerator.getInstance().getMap())
//				{
//					System.out.println(mp.getCoordinates()[0] + " ," + mp.getCoordinates()[1]);
//				}
//				 MapPoint mp = MapGenerator.getInstance().getPoint(5000, 0);
				 int index = MapGenerator.getInstance().getPointMapIndex(5000, 0);
				 System.out.println("************************************" );
				 System.out.println(index);

				 ArrayList<MapPoint> mps =  MapGenerator.getInstance().getMap();
				 System.out.println(" signal is " + mps);
//				 System.out.println("MP is " + mp);
			}
		});
		
		particleGenButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Localizer.getInstance().generateParticles();
				
			}
		});
		
		localizeButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				Toast.makeText(MapGenerationView.this,"localizing...", Toast.LENGTH_SHORT).show();
				Localizer.getInstance().localize();
				// generateMap();
				// MapGenerator.getInstance().parseMapFile();
			}
		});

	}

//	public void parseMapFile() {
//		String[] signal = null;
//		int gCounter = 0, counter = 0, notEvent = 0;
//		HashMap<String, Integer> hm = new HashMap<String, Integer>();
//		HashMap<String, Integer> wifiCounter = new HashMap<String, Integer>();
//		// open the file for reading
//		InputStream instream;
//		try {
//			instream = assetManager.open("signal2.csv"); // openFileInput("signal2.csv");
//			// if file the available for reading
//			if (instream != null) {
//				// prepare the file for reading
//				InputStreamReader inputreader = new InputStreamReader(instream);
//				BufferedReader buffreader = new BufferedReader(inputreader);
//
//				String line;
//				MapPoint mp;
//
//				while ((line = buffreader.readLine()) != null) {
//
//					signal = line.split(",");
//
//					if (signal.length % 2 == 0) // if it is even number of elements
//					{
//						for (int i = 4; i < signal.length - 1; i += 2)
//						{
//							if (wifiCounter.containsKey(signal[i])) {
//								int temp = wifiCounter.get(signal[i]);
//								wifiCounter.put(signal[i], temp + 1);
//							} else {
//								wifiCounter.put(signal[i], 1);
//							}
//						}
//						/*
//						 * int xCor = Integer.parseInt(signal[1]); int yCor =
//						 * Integer.parseInt(signal[3]); int[] cors = {xCor,
//						 * yCor}; mp = new MapPoint( cors, hm); //create a map
//						 * point MapGenerator.getInstance().putPoint(mp);
//						 * for(int i = 0; i < signal.length; ++i) {
//						 * //System.out.println(signal[i]); }
//						 */
//					} else {
//						notEvent++;
//						System.out.println("Bad Line Number: " + counter);
//					}
//				}
//			}
//		} catch (FileNotFoundException e) {
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//
////		System.out.println("Not Event is: " + notEvent);
////		for (String s : wifiCounter.keySet()) {
////			//System.out.println(s + " TIMES: " + wifiCounter.get(s));
////		}
//		HashMap<String,Integer> newWifi = (HashMap<String, Integer>) wifiCounter.clone();
//		for (String s : wifiCounter.keySet()) {
//
//			if (wifiCounter.get(s) < 33) {
//				newWifi.remove(s);
//			}
//		}
//		
////		for (String s : newWifi.keySet()) {
////			System.out.println(s + " TIMES: " + newWifi.get(s));
////		}
//		
//		InputStream istream;
//		try {
//			istream = getAssets().open("signal2.csv"); // openFileInput("signal2.csv");
//			// if file the available for reading
//			int counter2 = 0;
//			if (istream != null) {
//				// prepare the file for reading
//				InputStreamReader inputreader = new InputStreamReader(istream);
//				BufferedReader buffreader = new BufferedReader(inputreader);
//
//				String line;
//				MapPoint mp;
//
//				while ((line = buffreader.readLine()) != null) {
//					signal = line.split(",");
//					counter2++;
//					if (signal.length % 2 == 0) // if it is even number of elements
//					{
//						HashMap<String, Integer> wifiHm = new HashMap<String, Integer>();
//						for (int i = 4; i < signal.length - 1; i += 2) // point
//						{
//							if (newWifi.containsKey(signal[i])) {
//								wifiHm.put(signal[i], Integer.parseInt(signal[i+1]));
//							}
//						}
//						int xCor = Integer.parseInt(signal[1]); 
//						int yCor = Integer.parseInt(signal[3]); 
//						int[] cors = {xCor, yCor}; 
//						mp = new MapPoint(cors, wifiHm); //create a map
//						MapGenerator.getInstance().putPoint(mp);
//						//ArrayList<MapPoint> mps = MapGenerator.getInstance().getMap();
//						//System.out.println("msp is " + mps);
////						hm.clear();
////						ArrayList<MapPoint> mps = MapGenerator.getInstance().getMap();
////						System.out.println("msp is " + mps);
//						//System.out.println("msp wifi is " + mps.get(0).getWifiID());
//					}
//				}
//				
//				System.out.println("*********COUNT is *******" + counter2);
//				
//				ArrayList<MapPoint> mps = MapGenerator.getInstance().getMap();
//				
//				System.out.println("**********MAP size is ************************" + mps.size());
//				
//				for(MapPoint mpp: MapGenerator.getInstance().getMap())
//				{
//					System.out.println("Map point x: " + mpp.getCoordinates()[0] + " y: " + mpp.getCoordinates()[1]);
//
//				}
////				System.out.println("msp is " + mps);
//			}
//
//		} catch (FileNotFoundException e) {
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//
//	}

//	protected void generateMap() {
//		while (true) {
//			// random generate orientation
//			// if will hit the wall
//			// BREAK
//
//			// if not hit the wall then
//			{
//				// move(orientation, 500) move 500 millimeter in that
//				// orientatioin
//				// send wifi signal back to server
//			}
//			//
//		}
//	}
	
	private void sendProb()   	//network connection has to run in a separate thread
	{
		 new Thread(new Runnable() { 
	            public void run(){
	            	//send the coordinates and probability for each of the map points
	            	for(MapPoint mpp: MapGenerator.getInstance().getMap())
	        		{
	        			Helper.sendPacket(mpp.getCoordinates()[0] + "," + mpp.getCoordinates()[1] + "," + 10);
	        		}
	            }
	    }).start();	
	}

//	private void sendWifiSignal() {
//		String signal = "";
//		wifi.startScan();
//		List<ScanResult> scanResults = wifi.getScanResults();
//		for (ScanResult sr : scanResults) {
//			Log.i("SignalTag", sr.toString());
//			Helper.sendPacket("x: ," + xPos + ", y: ," + yPos + ", " + sr.BSSID + ", "
//					+ sr.level);
//			// MapGenerator.getInstance().putPoint(currentPoint)
//			// sendPacket( sr.toString());
//		}
//	}

//	public void wifiScan(View view) {
//
//	}

	public void move(double turn, int forward) {
		btThread.goForward((int) forward);
		btThread.stopDrive();

		orientation += turn;// + new Random().nextGaussian()*turn_noise;
		orientation %= 360;
		int distance = forward; // + new Random().nextGaussian()*forward_noise;
		xPos = (int) (distance * Math.cos(orientation / 360 * 2 * Math.PI) + xPos);
		yPos = (int) (distance * Math.sin(orientation / 360 * 2 * Math.PI) + yPos);
	}
}
